from django.db.models import Q
from django.http import JsonResponse
from rest_framework.views import APIView
from .models import Region
from utils.utils import validateError, serializerJSON, responseSuccess, responseError
from .validate import EditValidate, AddValidate
from .serializers import RegionLazyTreeSerializer, DetailSerializer, SelectSerializer

# 基础配置-行政区划-树结构
class LazyTreeAPI(APIView):
    def get(self,req):
        parentCode = req.query_params.dict().get('parentCode',None)
        objs = Region.objects.filter(parentCode=parentCode)
        serializers = RegionLazyTreeSerializer(objs, many=True)
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 详情
class DetailAPI(APIView):
    def get(self, req):
        code = req.query_params.dict().get("code")
        if not code:
            return JsonResponse(responseError('code不能为空'), safe=False)
        serializer = DetailSerializer(Region.objects.get(code=code))
        return JsonResponse(responseSuccess(serializer.data), safe=False)

# 新增/修改
class SubmitAPI(APIView):
    def post(self,req):
        data = req.data
        edit_id = data.get('code')
        region = Region.objects.filter(code=edit_id)
        if region.exists():
            form = EditValidate(region.first(), data=data)
        else:
            form = AddValidate(data=data)
        if form.is_valid():
            if region.exists():
                obj = form.update(region.first(), form.validated_data)
            else:
                obj = form.create(form.validated_data)
            return JsonResponse(responseSuccess(str(obj.pk)), safe=False)
        # 格式化错误信息
        arr = validateError(form.errors)
        return JsonResponse(responseError(arr), safe=False)
    
class RemoveAPI(APIView):
    def post(self,req):
        id = req.query_params.dict().get('id')
        if not id:
            return JsonResponse(responseError('id不能为空'), safe=False)
        if not Region.objects.filter(id=int(id)).exists():
            return JsonResponse(responseError('删除对象不存在'), safe=False)
        for i in Region.objects.filter(id=int(id)):
            if i.region_set.exists():
                return JsonResponse(responseError('请先删除子级数据'), safe=False)
        result = Region.objects.filter(id=int(id)).delete()
        if result:
            return JsonResponse(responseSuccess(), safe=False)
        return JsonResponse(responseError('删除失败'), safe=False)


class SelectAPI(APIView):
    def get(self,req):
        code = req.query_params.dict().get('code', None)
        q = Q(parentCode=None)
        if code:
            q = Q(code=code)
        objs = Region.objects.filter(q)
        serializers = SelectSerializer(objs, many=True)
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)
